package com.irain.pp.tool;


import com.irain.pp.tool.exception.HttpResponseException;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.HttpURLConnection;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @date 2017/10/26 19:43
 */
public class HttpClientUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    private static int maxTotal = 200;
    private static int defaultMaxPerRout = 40;
    private static int retryTime = 5;
    private static Map<String,Integer> routMap = new HashMap<>();
    private static CloseableHttpClient httpClient = null;

    private HttpClientUtils(){}

    public static String execute(HttpUriRequest request){
        CloseableHttpResponse response;
        try {
            response = getHttpClient().execute(request);
            if (response == null){
                throw new HttpResponseException("No response!");
            }
            String result = EntityUtils.toString(response.getEntity());
            int httpCode = response.getStatusLine().getStatusCode();
            if (httpCode != HttpURLConnection.HTTP_OK){
                throw new HttpResponseException("响应信息异常：[" + httpCode + "]\n" + result);
            }
            return result;
        } catch (IOException e){
            throw new HttpResponseException(e);
        }
    }


    /**
     * 请求重试处理
     */
    private static final HttpRequestRetryHandler HTTP_REQUEST_RETRY_HANDLER = (exception, executionCount, context) -> {
        // 如果已经重试了5次，就放弃
        if (executionCount >= retryTime) return false;
        // 如果服务器丢掉了连接，那么就重试
        if (exception instanceof NoHttpResponseException) return true;
        // 不要重试SSL握手异常
        if (exception instanceof SSLHandshakeException)return false;
        // 连接被拒绝
        if (exception instanceof ConnectTimeoutException) return false;
        // 超时
        if (exception instanceof InterruptedIOException) return false;
        // 目标服务器不可达
        if (exception instanceof UnknownHostException) return false;
        // SSL握手异常
        if (exception instanceof SSLException) return false;
        HttpClientContext clientContext = HttpClientContext.adapt(context);
        HttpRequest request = clientContext.getRequest();
        // 如果请求是幂等的，就再次尝试
        if (!(request instanceof HttpEntityEnclosingRequest)) {
            return true;
        }
        return false;
    };

    /**
     * 创建ConnectionManager对象
     * @return
     */
    private static HttpClientConnectionManager createConnManager(){
        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("http", plainsf)
                .register("https", sslsf).build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        // 将最大连接数增加
        cm.setMaxTotal(maxTotal);
        // 将每个路由基础的连接增加
        cm.setDefaultMaxPerRoute(defaultMaxPerRout);
        for (Map.Entry<String,Integer> entry : routMap.entrySet()){
            String[] rout = entry.getKey().split(":");
            HttpHost httpHost = new HttpHost(rout[0], Integer.parseInt(rout[1]));
            // 将目标主机的最大连接数增加
            cm.setMaxPerRoute(new HttpRoute(httpHost), entry.getValue());
        }
        return cm;
    }
    /**
     * 创建HttpClient对象
     *
     * @return
     * @author SHANHY
     * @date 2015年12月18日
     */
    private static CloseableHttpClient createHttpClient(HttpClientConnectionManager connManager) {
        return httpClient = HttpClients.custom()
                .setConnectionManager(connManager)
                .setRetryHandler(HTTP_REQUEST_RETRY_HANDLER).build();
    }

    /**
     * 延迟初始化closableHttpClient
     * @return
     */
    private static CloseableHttpClient getHttpClient(){
        if (httpClient == null){
            synchronized (HttpClientUtils.class){
                if (httpClient == null){
                    HttpClientConnectionManager connManager = createConnManager();
                    httpClient = createHttpClient(connManager);
                }
            }
        }
        return httpClient;
    }
}
